package cn.service.impl;

import cn.dao.StreetDao;
import cn.dao.impl.StreetDaoImpl;
import cn.entity.Street;
import cn.service.StreetService;
import cn.utils.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;

public class StreetServiceImpl implements StreetService {

    private StreetDao streetDao = new StreetDaoImpl();

    @Override
    public Street loadStreet(long id) {
        Transaction tx = null;
        Street street = null;
        try {
            tx = HibernateUtil.getTransaction(HibernateUtil.currentSession());
            street = streetDao.load(id);
            HibernateUtil.commit(tx);
        } catch (HibernateException e) {
            e.printStackTrace();
            HibernateUtil.rollback(tx);
        }
        return street;
    }

    @Override
    public void deleteStreet(Street street) {
        Transaction tx = null;
        try {
            tx = HibernateUtil.getTransaction(HibernateUtil.currentSession());
            streetDao.delete(street);
            HibernateUtil.commit(tx);
        } catch (HibernateException e) {
            e.printStackTrace();
            HibernateUtil.rollback(tx);
        }
    }

    @Override
    public void updateStreet(Street street) {
        Transaction tx = null;

        try {
            tx = HibernateUtil.getTransaction(HibernateUtil.currentSession());
            Street streetUpdate = streetDao.load(street.getId());
            if (street.getName().length()!=0&&street.getName()!=null){
                streetUpdate.setName(street.getName());
            }
            if (street.getDistrict()!=null){
                streetUpdate.setDistrict(street.getDistrict());
            }
            HibernateUtil.commit(tx);
        } catch (HibernateException e) {
            e.printStackTrace();
            HibernateUtil.rollback(tx);
        }
    }

    @Override
    public void addNewStreet(Street street) {
        Transaction tx = null;
        try {
            tx = HibernateUtil.getTransaction(HibernateUtil.currentSession());
            streetDao.save(street);
            HibernateUtil.commit(tx);
        } catch (HibernateException e) {
            e.printStackTrace();
            HibernateUtil.rollback(tx);
        }
    }

}
